from coin2.service.otc.otc_service_pb2 import QueryProductInfoRequestProto
from xunkemgmt_client.client.api_client import XunkemgmtClient

from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo
import json

def get_pi_from_xunke():
  request = QueryProductInfoRequestProto()
  with XunkemgmtClient() as client:
    rsp = client.query_otc_product_infos(request)

  return rsp.product_infos


def merge_local(xunke_pis: list, path):
  with open(path, "r") as f:
    pis = json.load(f)["product_infos"]

  symbol_set = set()
  for pi in xunke_pis:
    symbol_set.add(pi["symbol"])

  for pi in pis:
    if pi["symbol"] in symbol_set:
      continue

    pi["price_ticksize"] = 1 / 1e8
    pi["qty_ticksize"] = 1 / 1e8

    xunke_pis.append(pi)

  return xunke_pis


def generate():
  mea = 'Options.Otc.v1'
  me = 'Options.Otc'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = get_pi_from_xunke()

  pis = []
  for info in data:
    native_symbol = info.symbol
    symbol = native_symbol
    native_base = info.base
    native_quote = info.quote

    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=1 / 1e8,
        qty_ticksize=1 / 1e8
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = merge_local(pis, "data/coin2/product_info/Options.Otc.v1.json")

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis

if __name__ == "__main__":
  print(json.dumps(generate(), indent=2))
